#include <stdio.h>
#include <string.h>

// cmd : command in shell
// buff: for result
// size: max lenth of buff
static char* shellcmd(char* cmd, char* buff, int size)
{
    char temp[256];
    FILE* fp = NULL;
    int offset = 0;
    int len;
    
    fp = popen(cmd, "r");
    if(fp == NULL)
    {
        return NULL;
    }

    while(fgets(temp, sizeof(temp), fp) != NULL)
    {
        len = strlen(temp);
        if(offset + len < size)
        {
            strcpy(buff+offset, temp);
            offset += len;
        }
        else
        {
            buff[offset] = 0;
            break;
        }
    }
    
    if(fp != NULL)
    {
        pclose(fp);
    }

    return buff;
}

int main(int argc, char *argv[])
{
    char result[256];
    char *p;
    p = shellcmd("ls", result, sizeof(result));
    printf("%s\n", result);
    printf("%s\n", p);
    printf("%p\n", result);
    printf("%p\n", p);
    return 0;
}
